package week05.question10;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * mysql db connection utils
 */
public class DBConnectionUtils {

    private static final String URL ="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai";
    private static final String ACCOUNT ="root";
    private static final String PASS ="123456";

    /**
     * acquire a connection from mysql db
     * @return a new connection
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public static Connection getDBConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(URL, ACCOUNT, PASS);
        return connection;
    }


    public static void close(Connection connection, PreparedStatement preparedStatement){
        if(preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
